#include "image.h"

GLuint load_texture(const char* file)
{
    SDL_Surface* surface = IMG_Load(file);
    if (surface == NULL)
    {
        fprintf(stderr, "ERROR: Couldn't load %s\n", file);
        return 0;
    }
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
    SDL_PixelFormat *format = surface->format;
    if (format->Amask)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
    } else {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
    }
    SDL_FreeSurface(surface);
    printf("Loaded %s as texture %d.\n", file, texture);
    return texture;
}
